import zh from './language/zh';
import en from './language/en';

// 语言类型
enum LangType {
	// 中文
	'zh' = 'zh-CN',
	// 英文
	'en' = 'en-US',
}

export class ValidatorMessage {
	// 当前语言类型
	private lang: string = LangType.en;

	constructor() {}

	// 当前map
	private get languageMap() {
		return this.lang === LangType.zh ? zh : en;
	}

	/**
	 * 序列化消息文本内容
	 * @param message
	 * @param data
	 * @returns
	 */
	parseMessageText(message: string, data: any[]): string {
		const regex = /\{(.*?)}/g;
		const parseMessage = message.replace(regex, (match, key) => {
			let parseIndex = match.slice(1, -1);
			return data[Number(parseIndex)] || '';
		});
		return parseMessage;
	}

	/**
	 * 序列化message
	 * @param typeReg
	 * @param params
	 */
	parse(typeReg: string, params: any[]): string {
		const [type, data] = typeReg.split(':');
		const errorMessage = this.languageMap[type];
		if (!errorMessage) {
			console.error(`Type for ${typeReg} message is not defined`);
			return `Type for ${typeReg} message is not defined`;
		}
		const parseMessage = this.parseMessageText(errorMessage, params);
		return parseMessage;
	}

	/**
	 * 切换语言
	 * @param type
	 */
	changeLang(type: LangType) {
		this.lang = type;
	}
}
